import React, { useEffect, useState } from 'react';
import { Button, Menu, Modal, Form, Input, Select, Dropdown, message, Popconfirm } from 'antd';
import { MailOutlined, MoreOutlined } from '@ant-design/icons';
import { mjSolution, addSolution, editSolution, removrSolution } from '@/services/ant-design-pro/solution';
import ImageUpload from '@/components/ImageUpload';

type SolutionCategoryMenuProps = {
  selectedKey: string;  
  onCategorySelect: (key: string) => void;
};


const SolutionCategoryMenu: React.FC<SolutionCategoryMenuProps> = ({
  selectedKey,
  onCategorySelect,
}) => {
  const [menuItems, setMenuItems] = useState<Array<{ key: string, label: JSX.Element }>>([]);
  const [menu, setMenu] = useState<any>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [currentKey, setCurrentKey] = useState<string | null>(null);
  const [currentItem, setCurrentItem] = useState<any>(null);

  const fetchMenuItems = async () => {
    try {
      const response = await mjSolution();
      const resList = response.data.map((item: { id: any; solutionName: string | number | boolean | React.ReactElement<any, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | React.ReactPortal | null | undefined; }) => {
        return {
          key: item.id,
          label: (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ width: '150px', overflow: 'hidden' }}>{item.solutionName}</div>
              <Dropdown
                trigger={['click']}
                overlay={
                  <Menu>
                    <Menu.Item key="edit" onClick={() => handleEdit(item)}>
                      修改
                    </Menu.Item>
                    <Popconfirm
                      title="删除"
                      description="确认删除解决方案么？"
                      onConfirm={() => handleDelete(item.id)}
                      okText="是"
                      cancelText="否"
                    >
                      <Menu.Item key="delete">
                        删除
                      </Menu.Item>
                    </Popconfirm>
                  </Menu>
                }
              >
                <MoreOutlined />
              </Dropdown>
            </div>
          ),
        };
      });
      setMenu(response.data);
      setMenuItems(resList);
    } catch (error) {
      console.error('Error fetching menu items:', error);
    }
  };

  useEffect(() => {
    fetchMenuItems();
  }, []);

  const handleSelect = (e: { key: React.SetStateAction<string | null>; }) => {
    onCategorySelect(e.key);
    setCurrentKey(e.key);
    const selectedItem = menu.find((item: { key: any; }) => item.key === e.key);
    setCurrentItem(selectedItem);
  };

  const handleItemClick = (e: { key: string | null; }) => {
    if (e.key === currentKey) {
      setModalVisible(true);
      const selectedItem = menu.find((item: { id: any; }) => item.id === e.key);
      setCurrentItem(selectedItem);
      form.setFieldsValue(selectedItem);
    }
  };

  const handleAdd = () => {
    setModalVisible(true);
    setCurrentItem(null);
    form.resetFields();
  };

  const handleOk = () => {
    form.validateFields().then(async values => {
      console.log('Form Values:', values);
      if (currentItem) {
        // Edit existing product
        await editSolution({ ...values, id: currentItem.id });
        message.success('编辑成功');
      } else {
        // Add new product
        await addSolution(values);
        message.success('添加成功');
      }
      fetchMenuItems();
      setModalVisible(false);
      form.resetFields();
    }).catch(info => {
      console.log('Validate Failed:', info);
    });
  };

  const handleCancel = () => {
    setModalVisible(false);
    form.resetFields();
  };

  const handleEdit = (item: any) => {
    setModalVisible(true);
    setCurrentItem(item);
    form.setFieldsValue(item);
  };

  const handleDelete = async (id: any) => {
    try {
      await removrSolution({ id });
      message.success('删除成功');
      fetchMenuItems();
    } catch (error) {
      console.error('Error deleting item:', error);
    }
  };

  return (
    <div>
      <Menu
        onSelect={handleSelect}
        style={{ width: 256 }}
        selectedKeys={[currentKey || selectedKey]}
        defaultOpenKeys={['sub1']}
        mode="inline"
        items={[
          {
            key: 'sub1',
            label: (
              <span>
                <MailOutlined />
                <span>解决方案</span>
              </span>
            ),
            children: [
              ...menuItems,
              {
                key: 'add-button',
                type: 'group',
                label: (
                  <div style={{ textAlign: 'center', marginTop: '16px' }}>
                    <Button type="primary" onClick={handleAdd}>
                      添加
                    </Button>
                  </div>
                ),
              },
            ],
          },
        ]}
      />
      <Modal
        title={currentItem ? "修改解决方案" : "添加解决方案"}
        open={modalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="solutionName" label="解决方案名称" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="title" label="banner标题" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="contentDesc" label="banner描述" rules={[{ required: true }]}>
            <Input.TextArea />
          </Form.Item>
          <Form.Item name="pic" label="banner图" rules={[{ required: true }]}>
            <ImageUpload value={form.getFieldValue('pic')} onChange={(url: string) => form.setFieldsValue({ pic: url })} />
          </Form.Item>
          <Form.Item name="alt" label="图片alt" >
            <Input />
          </Form.Item>
          <Form.Item name="firstDesc" label="服务及优势描述" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="secondDesc" label="服务案例描述" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="threeDesc" label="解决方案描述" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="router" label="前端路由" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="seoTitle" label="seo标题">
            <Input />
          </Form.Item>
          <Form.Item name="seoDesc" label="seo描述">
            <Input />
          </Form.Item>
          <Form.Item name="seoKeys" label="seo关键词">
            <Input />
          </Form.Item>
       
        
          <Form.Item name="sort" label="排序">
            <Input type="number" />
          </Form.Item>
         
        </Form>
      </Modal>
    </div>
  );
};

export default SolutionCategoryMenu;